package org.itli.jnsocket.Service.ServiceImpl;

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.itli.jnsocket.Mapper.GoodsMapper;
import org.itli.jnsocket.Pojo.GoodsCategory;
import org.itli.jnsocket.Service.GoodsService;
import org.itli.jnsocket.VTO.GoodCatrgory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class GoodsServiceImpl implements GoodsService {

    GoodsMapper mapper;

    @Autowired
    public void setMapper(GoodsMapper mapper) {
        this.mapper = mapper;
    }

    Gson gson;

    @Autowired
    public void setGson(Gson gson) {
        this.gson = gson;
    }

    @Override
    public String AllCatrgory() {
        List<GoodsCategory> goodsCategories = mapper.AllCategory();
        //下面的逻辑是将子类的名称放到父类的数组中
        for(GoodsCategory goodsCategory : goodsCategories) {
            if(goodsCategory.getPid()!=0){
                for(GoodsCategory g:goodsCategories) {
                    if(g.getId()==goodsCategory.getPid()){
                         log.info("父 id"+g.getId()+"子 id"+goodsCategory.getId());
                         g.showSubCategories.add(goodsCategory);
                         break;
                    }
                }
            }
        }
        String json = gson.toJson(goodsCategories);
        return json;
    }

    @Override
    public String newCategory(String username, String name, String weight) {
        try{
            int i = mapper.AddCategory(name, weight, username);
            if(i==0){
                return "0";
            }else {
                return "1";
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            return "error";
        }
    }

    @Override
    public String AddSubCategory(GoodCatrgory goodCatrgory,String username) {
        try{
            int i = mapper.AddSubCategory(goodCatrgory.getName(), goodCatrgory.getWeight(), username, goodCatrgory.getPid());
            if(i==0){
                return "0";
            }
            else {
                return "1";
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            return "error";
        }

    }

    @Override
    public String DeleteCategory(String name) {
        try{
            mapper.DeleteCategory(name);
            return "1";
        } catch (Exception e) {
            log.error(e.getMessage());
            return "error";
        }
    }
}
